package com.aiinterview.subjectservice.config;


import com.aiinterview.common.constant.MessageConstant;
import com.aiinterview.common.entity.Result;
import com.aiinterview.common.exception.BaseException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        return Result.fail(ex.getMessage());
    }

    @ExceptionHandler
    public Result sqlexception(SQLIntegrityConstraintViolationException ex){
        String msg = ex.getMessage();
        if(msg.contains("Duplicate entry")){
            String []str = msg.split(" ");
            String username = str[2];
            msg = username + MessageConstant.ALREADY_EXISTS;
        }
        return Result.fail(msg);
    }

}
